package com.atguigu.lease.web.admin.custom.config.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @Author zhaolingqiao
 * @CreateTime 2024/12/9
 * 自定义枚举转换器工厂，StringToBaseEnumConverterFactory
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    /**
     * 获取类型转换器对象，
     * 遍历，枚举元素集合，
         * 找到对应枚举，并返回
         * 找不到，抛异常
     * @param targetType
     * @return
     * @param <T>
     */
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()) {
                    if(enumConstant.getCode() == Integer.parseInt(source)){
                        return enumConstant;
                    }
                }
                throw new RuntimeException("数据类型不匹配！");
            }
        };
    }
}
